const dao = require('./base');

module.exports = {

    relationList: async function (condition, fields = "*", by = []) {
        let sql = `SELECT ${fields} from afc_relation_view where del_flag=0`;
        let pre = [];
        if (condition.pid !== undefined && condition.pid !== '') {
            sql += ` and pid = ?`;
            pre.push(parseInt(condition.pid));
        }
        if (condition.cid !== undefined && condition.cid !== '') {
            sql += ` and cid = ?`;
            pre.push(parseInt(condition.cid));
        }
        if (condition.cc_id !== undefined && condition.cc_id !== '') {
            sql += ` and cc_id = ?`;
            pre.push(parseInt(condition.cc_id));
        }
        sql = dao.by(sql, by)

        let limit = dao.limit(sql, condition, pre);
        sql = limit.sql;
        pre = limit.pre;

        let data;
        await dao.query(sql, pre).then((results, fields) => {
            data = results;
        }).catch((err) => {
            data = {err: err}
        });
        return data;
    },

    relationAdd: async function (fields = []) {
        let sql = "insert into afc_relation (pid,cid,cc_id) values(?,?,?)";
        let pre = [];
        let data;
        pre.push(fields.pid);
        pre.push(fields.cid);
        pre.push(fields.cc_id);

        await dao.query(sql, pre).then((results, fields) => {
            data = results;
        }).catch((err) => {
            data = {err: err}
        });
        return data;
    },

    relationUpdate: async function (condition = {}, fields = {}) {
        let sql = "update afc_relation set ";
        let pre = [];
        let data;
        if (fields.pid !== undefined && fields.pid !== '') {
            sql = dao.update_sql_splice(sql, "pid");
            pre.push(fields.pid);
        }
        if (fields.cid !== undefined && fields.cid !== '') {
            sql = dao.update_sql_splice(sql, "cid");
            pre.push(fields.cid);
        }
        if (fields.cc_id !== undefined && fields.cc_id !== '') {
            sql = dao.update_sql_splice(sql, "cc_id");
            pre.push(fields.cc_id);
        }
        if (fields.del_flag !== undefined && fields.del_flag !== '') {
            sql = dao.update_sql_splice(sql, "del_flag");
            pre.push(fields.del_flag);
        }
        if (condition.id !== undefined && condition.id !== '') {
            sql += ` where id = ?`;
            pre.push(condition.id);
        } else {
            return;
        }

        await dao.query(sql, pre).then((results, fields) => {
            data = results;
        }).catch((err) => {
            data = {err: err}
        });
        return data;
    },


};
